package com.qys.controller;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.qys.fileservice.fileService;
import com.qys.service.loginService;

@Controller
@MultipartConfig
public class loginTest {
	@Autowired
	private loginService service;
	private fileService fileService;
	
	@RequestMapping(value="/logindo",method=RequestMethod.POST)
	@ResponseBody
	public ModelAndView login(@RequestParam("username")String username,@RequestParam("pwd")String pwd,HttpServletRequest req,HttpServletResponse resp){
		int num = service.selectUser(username, pwd);
		 ModelAndView retMap1 = new ModelAndView(); 
		 retMap1.setViewName("main");
		 ModelAndView retMap2 = new ModelAndView(); 
		 retMap2.setViewName("login");
		if(num>=1){
			HttpSession session = req.getSession();
			System.out.println("session信息为："+session);
			Cookie cookieToken = new Cookie("token",username);
			cookieToken.setMaxAge(15);
			resp.addCookie(cookieToken);
			return retMap1;
			} else {
			return retMap2;
		}
	}
	
	@RequestMapping("/upLoadAndDown")	
	public ModelAndView logintoo(HttpServletRequest req){
		 ModelAndView retMap3 = new ModelAndView(); 
		 retMap3.setViewName("fileud");
		 ModelAndView retMap4 = new ModelAndView(); 
		 retMap4.setViewName("login");
		 boolean b = false;
		 Cookie[] cookieTokens = req.getCookies();
		 if(cookieTokens==null){
				b=false;
			}
			else{
				for(Cookie cookie:cookieTokens){
					if("token".equals(cookie.getName())){
						b=true;
				System.out.println("cookie的键值对信息："+cookie.getName()+":"+cookie.getValue());
					}
	}
				
				}
		 if(b==true){
				return retMap3;
				} else {
			return retMap4;
		}
	}
	

	@RequestMapping("/toServerUp")
	@ResponseBody
	public void myPostUp(MultipartFile file,HttpServletRequest request,HttpServletResponse resp) throws ClientProtocolException, IOException{

		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		// 生成一个HttpPost请求
		HttpPost httpPost = new HttpPost("http://localhost:1234/server/upload");
		
		MultipartEntityBuilder mEntity = MultipartEntityBuilder.create();
		mEntity.addBinaryBody("file", file.getBytes());
		String fileName = URLEncoder.encode(file.getOriginalFilename(), "UTF-8");
		mEntity.addTextBody("fileName", fileName);
		HttpEntity entity = mEntity.build();
		httpPost.setEntity(entity);
		
		CloseableHttpResponse response = null;
		// 执行post请求
 
		try {
			response = httpClient.execute(httpPost);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		String result="";
		HttpEntity resentity = response.getEntity();
 
			try {
				if(entity != null) {
					result = EntityUtils.toString(entity);
				}
			} catch (ParseException | IOException e) {
				e.printStackTrace();
			}finally {
				try {
					if(response != null) {
						response.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			 try { 
				 fileService.upFile(fileName); 
			} catch (SQLException e) {
				e.printStackTrace();
			}
				System.out.println("上传成功,信息存入数据库，并且自动生成文件夹");
				
	}
	
	@RequestMapping("/toServerDown")
	@ResponseBody
	public void myPostDown(MultipartFile file,HttpServletRequest request,HttpServletResponse resp) throws ClientProtocolException, IOException, URISyntaxException, ServletException{
		LocalDate date = LocalDate.now();
		int month = date.getMonthValue();
		int today = date.getDayOfMonth();
		String path = "E:\\C\\"+month+"月"+today+"日";
		File filetoo = new File(path);
		File[] files = filetoo.listFiles();
		String filename = files[0].getName();
		double filesize = files[0].length();
		
		try {
		int num = fileService.proving(filename);
		if(num>=1){
			fileService.downFile(filename, filesize);
			resp.addHeader("content-disposition", "attachment;filename="+filename);//获取文件头信息
			FileUtils.copyFile(files[0], resp.getOutputStream());//将上面从下载源路径中获取的一个文件复制进响应地址。
			System.out.println("下载成功，文件名以及大小已经存入数据库");
		}
		else{
			System.out.println("该文件不是你上传，你无权下载");
			request.getRequestDispatcher("/WEB-INF/page/false.jsp").forward(request,resp);
		} 
						
	} catch (SQLException e) {
		e.printStackTrace();
	}
		
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		resp.setHeader("content-disposition", "attachment;filename=" + filename);
		List<NameValuePair> params = new ArrayList();
		params.add(new BasicNameValuePair("fileName", filename));
	URI uri = new URIBuilder().setScheme("http").setHost("localhost")
				.setPort(1234).setPath("/server/down")
				.setParameters(params).build();

		HttpPost httpPost = new HttpPost(uri);
		CloseableHttpResponse response = httpClient.execute(httpPost);
		MultipartEntityBuilder mEntity = MultipartEntityBuilder.create();
		HttpEntity entity = mEntity.build();
		HttpEntity resentity = response.getEntity();
		String result = EntityUtils.toString(entity);
		
		try {
			if(response != null) {
				response.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
 
	}
	
}
